<?php
namespace app\common\model;

use app\common\model\UserDownloadTimes;
use app\common\model\UserMain;
use app\common\model\UserReward;
use think\facade\Db;
use think\facade\Request;
use think\Model;
use think\model\concern\SoftDelete;

class UserFission extends Model
{
    use SoftDelete;
    protected $pk                = '';
    protected $deleteTime        = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $type              = [
        'create_time' => 'timestamp',
        'delete_time' => 'timestamp',
    ];

    public static function onBeforeInsert($data)
    {
        $data->create_time = Request::time();
        $data->create_ip   = Request::ip();
    }

    public static function onAfterInsert($data)
    {
        global $_G;
        $param = $data->toArray();
        if (empty($param['spread_uid'])) {
            return true;
        }

        $floor = ($param['floor'] ?? 0) + 1;
        if ($_G['setting']['user_fission_reward_lv'] >= $floor && !UserDownloadTimes::where([['create_ip', '=', Request::ip()], ['from', '=', 'fission']])->find()) {
            $day              = date('Y-m-d');
            $reward_count     = UserReward::where([['uid', '=', $param['spread_uid']], ['day', '=', $day]])->find();
            $reward_count_all = UserReward::where('uid', '=', $param['spread_uid'])->sum('times');
            $reward_times     = empty($reward_count) ? 0 : $reward_count['times'];
            if (($_G['setting']['user_fission_reward_day_times'] == 0 || ($_G['setting']['user_fission_reward_day_times'] > 0 && $reward_times < $_G['setting']['user_fission_reward_day_times'])) &&
                ($_G['setting']['user_fission_reward_max_times'] == 0 || ($_G['setting']['user_fission_reward_max_times'] > 0 && $reward_count_all < $_G['setting']['user_fission_reward_max_times']))
            ) {
                $rewardData = [];
                foreach ($_G['setting']['user_fission_reward']['out_time'] as $site_id => $out_time) {
                    if ($out_time < 0 || empty($_G['setting']['user_fission_reward']['times'][$site_id]) || $_G['setting']['user_fission_reward']['times'][$site_id] <= 0) {
                        continue;
                    }
                    $rewardData[] = [
                        'uid'      => $param['spread_uid'],
                        'site_id'  => $site_id,
                        'times'    => $_G['setting']['user_fission_reward']['times'][$site_id],
                        'from'     => 'fission',
                        'summary'  => '推广用户获取奖励',
                        'out_time' => empty($out_time) ? 0 : (Request::time() + ($out_time * 3600)),
                        'status'   => 1,
                    ];
                }
                if (!empty($rewardData)) {
                    (new UserDownloadTimes)->saveAll($rewardData);
                    if (empty($reward_count)) {
                        UserReward::create([
                            'uid'   => $param['spread_uid'],
                            'day'   => $day,
                            'times' => 1,
                        ]);
                    } else {
                        $reward_count->times = Db::raw('times+1');
                        $reward_count->save();
                    }
                }
            }
        }
        if (!empty($param['fission_uid']) && ($_G['setting']['user_fission_lv'] == 0 || $_G['setting']['user_fission_lv'] >= $floor)) {
            $up_user = UserMain::where('uid', '=', $param['spread_uid'])->find();
            if (!empty($up_user['up_uid']) && !self::where([['spread_uid', '=', $up_user['up_uid']], ['fission_uid', '=', $param['fission_uid']]])->find()) {
                self::create([
                    'spread_uid'  => $up_user['up_uid'],
                    'fission_uid' => $param['fission_uid'],
                    'floor'       => $floor,
                ]);
            }
        }
    }

    public function spreadUser()
    {
        return $this->belongsTo(UserMain::class, 'fission_uid');
    }
}
